import { Injectable } from '@angular/core';
import { tap, delay } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoginUser } from 'src/app/shared/models';
import { Router } from '@angular/router';
import { MockApiService } from './api-mock.service';
import { ApiService, JsonResult } from './api.service';
/**
 * 登录请求
 */
@Injectable({
  providedIn: 'root'
})
export class LoginService {
  isLoggedIn = false; // 登录状态：默认为未登录
  resData = {};
  constructor(
    private router: Router,
    private mockApiservice: MockApiService,
    private http: HttpClient,
    private apiService: ApiService
  ) { }

  redirectUrl: string;

  logout(): Observable<LoginUser> {
    return this.apiService.post('/logout').pipe(
      map((jsonResult: JsonResult<LoginUser>) => jsonResult.data)
    );
  }

  getLoginMockData() {
    return this.mockApiservice.fetch('login.json').pipe(
      delay(1000),
      tap(val => this.isLoggedIn = true));
  }

  isLogin(username: string, password: string): Observable<LoginUser> {
    console.log('请求登录===》' + username + password);
    this.resData = {
      'username': username,
      'password': password
    };
    return this.apiService.post('/login', this.resData).pipe(
      map((jsonResult: JsonResult<LoginUser>) => jsonResult.data)
    );
  }

}
